package com.yunlong.softpark.service.impl;

import com.yunlong.softpark.core.exception.SysException;
import com.yunlong.softpark.dto.*;
import com.yunlong.softpark.entity.ColumnEntity;
import com.yunlong.softpark.entity.IntroduceEntity;
import com.yunlong.softpark.entity.PlatesEntity;
import com.yunlong.softpark.entity.SortEntity;
import com.yunlong.softpark.form.CreateColumnForm;
import com.yunlong.softpark.form.UpdateColumnForm;
import com.yunlong.softpark.mapper.*;
import com.yunlong.softpark.redis.RedisRepository;
import com.yunlong.softpark.service.ColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Cui
 * @Date: 2020/7/27
 * @Description:
 */
@Service
public class ColumnServiceImpl implements ColumnService {

    @Autowired
    ColumnMapper columnMapper;

    @Autowired
    IntroduceMapper introduceMapper;

    @Autowired
    PlatesMapper platesMapper;

    @Autowired
    SortMapper sortMapper ;

    @Autowired
    SoftwareMapper softwareMapper;

    @Autowired
    RedisRepository redisRepository;

    /**
     * 返回排行榜下载次数的前十位
     *
     * @return
     */
    @Override
    public List<RankDto> getRankData() {
        List<RankDto> list = columnMapper.selectDataForRank();
        list.sort(Comparator.comparing(RankDto::getDownloads).reversed());
        List<RankDto> rankDtos = new ArrayList<>();
        if (list.size() > 10) {
            for (int i = 0; i < 10; i++) {
                rankDtos.add(list.get(i));
            }
        } else {
            for (int i = 0; i < list.size(); i++) {
                rankDtos.add(list.get(i));
            }
        }
        return rankDtos;
    }

    /**
     * 返回栏目的简单介绍
     *
     * @return
     */
    @Override
    public ColumnSimDto getSimpleIntroduce(String columnId) {
        ColumnSimDto columnSimDto = null;
        try {
            columnSimDto = columnMapper.selectDataForSimpleColumn(columnId);
        } catch (NullPointerException e) {
            System.out.println("查询失败或者数据库信息空！");
        }
        return columnSimDto;
    }

    /**
     * 返回栏目的详细介绍
     *
     * @param columnId
     * @return
     */
    @Override
    public ColumnDetailDto getDetailIntroduce(String columnId) {
        ColumnEntity columnEntity = columnMapper.selectByColumnId(columnId);
        ColumnDetailDto columnDetailDto = null;
        try {
            columnDetailDto = introduceMapper.selectDataForDetailColumn(columnEntity.getIntroduceId());
            String updateLog = columnDetailDto.getUpdateLog();
            char[] chars = updateLog.toCharArray();
            if (chars[0] == ' ') {
                columnDetailDto.setUpdateLog(null);
            }
        }catch (NullPointerException e){
            System.out.println("查询失败或者数据库信息空！");
        }
        return columnDetailDto;
    }

    /**
     * 将栏目的详细信息转换成list
     *
     * @param columnDetailDto
     * @return
     */
    @Override
    public List<ColumnDetailListDto> changeColumnDetailDtoToList(ColumnDetailDto columnDetailDto) {
        List<ColumnDetailListDto> listDtos = new ArrayList<>();


        try {
            ColumnDetailListDto columnDetailListDto1 = new ColumnDetailListDto();
            columnDetailListDto1.setName("基本信息");
            columnDetailListDto1.setValue(columnDetailDto.getBriefIntro());
            listDtos.add(columnDetailListDto1);

            ColumnDetailListDto columnDetailListDto2 = new ColumnDetailListDto();
            columnDetailListDto2.setName("主要功能");
            columnDetailListDto2.setValue(columnDetailDto.getFunction());
            listDtos.add(columnDetailListDto2);

            ColumnDetailListDto columnDetailListDto3 = new ColumnDetailListDto();
            columnDetailListDto3.setName("软件特色");
            columnDetailListDto3.setValue(columnDetailDto.getCharacter());
            listDtos.add(columnDetailListDto3);

            ColumnDetailListDto columnDetailListDto4 = new ColumnDetailListDto();
            columnDetailListDto4.setName("更新日志");

            String[] strs = columnDetailDto.getUpdateLog().split("``");
            List<String> list = Arrays.asList(strs);
            columnDetailListDto4.setValue(list);
            listDtos.add(columnDetailListDto4);

        }catch (NullPointerException e){

            System.out.println("查询失败或者数据库信息空！");
        }


        return listDtos;
    }



    /**
     * 创建栏目
     *
     * @param createColumnForm
     * @param userId
     * @return
     */
    @Override
    public String createColumn(CreateColumnForm createColumnForm, String userId) {

        String columnId = UUID.randomUUID().toString().replace("-", "");
        String introduceId = UUID.randomUUID().toString().replace("-", "");
        //创建栏目
        columnMapper.insertColumn(
                columnId,
                createColumnForm.getColumnName(),
                createColumnForm.getParentId(),
                createColumnForm.getColumnLogo(),
                createColumnForm.getColumnWeb(),
                createColumnForm.getWebIntroduce(),
                createColumnForm.getColumnType(),
                createColumnForm.getLicense(),
                introduceId,
                0,
                createColumnForm.getShowPic(),
                0,
                0,
                userId);
        //添加介绍
        introduceMapper.insertIntroduce(introduceId, createColumnForm.getBriefIntro(), createColumnForm.getFunction(),
                createColumnForm.getCharacter(), new SimpleDateFormat("yyyy-MM-dd HH:mm")
                        .format(new Date())+":创建了"+createColumnForm.getColumnName());
        return columnId;
    }

    /**
     * 《个人页面》
     * 根据column回显出在个人页面的栏目相关信息
     *
     * @param columnId
     * @return columnPersonalDataDto
     */
    @Override
    public ColumnPersonalDataDto getPersonalDataDto(String columnId) {
        ColumnPersonalDataDto columnPersonalDataDto = new ColumnPersonalDataDto();

        try {
            ColumnEntity columnEntity = columnMapper.selectByColumnId(columnId);
            //设置栏目名
            columnPersonalDataDto.setColumnName(columnEntity.getColumnName());
            //设置栏目logo
            columnPersonalDataDto.setColumnLogo(columnEntity.getColumnLogo());
            //设置栏目官网
            columnPersonalDataDto.setColumnWeb(columnEntity.getColumnWeb());
            //设置官方介绍
            columnPersonalDataDto.setWebIntroduce(columnEntity.getWebIntroduce());
            //设置授权信息
            columnPersonalDataDto.setLicense(columnEntity.getLicense());
            //设置页面展示
            columnPersonalDataDto.setShowPic(columnEntity.getShowPic());
            //设置软件类型
            columnPersonalDataDto.setColumnType(columnEntity.getColumnType());

            //--------->以下是软件介绍中的内容
            IntroduceEntity introduceEntity = introduceMapper.selectAllData(columnEntity.getIntroduceId());
            //设置栏目简介
            columnPersonalDataDto.setBriefIntro(introduceEntity.getBriefIntro());
            //设置栏目功能
            columnPersonalDataDto.setFunction(introduceEntity.getFunction());
            //设置栏目特色
            columnPersonalDataDto.setCharacter(introduceEntity.getCharacter());

            //获取plate ---> sort 的二级菜单
            List<PlateDto> plateDtosList = getPlatesTwiceMenu();
            columnPersonalDataDto.setPlateDtos(plateDtosList);
            //获取trueIndex --- > plateId和SortId
            Map<String,Integer> trueIndex = new HashMap<>();
            trueIndex.put("sortId",columnEntity.getParentId());
            List<SortEntity> sort = softwareMapper.getSort();
            trueIndex.put("plateId",0);
            columnPersonalDataDto.setTrueIndex(trueIndex);
        }catch (NullPointerException e){
            System.out.println("查询失败或者数据库信息空！");
        }


        return columnPersonalDataDto;
    }

    /**
     * 《个人页面》
     * @return
     * 返回plate ---> sort 的二级菜单
     */
    @Override
    public List<PlateDto> getPlatesTwiceMenu() {
        List<PlateDto> plateDtosList = new ArrayList<>();
        try {
            List<PlatesEntity> platesEntityList = platesMapper.selectAllFormPlatesForm();
            List<SortEntity> sort = softwareMapper.getSort();
            List<PlateDto> collect1 = platesEntityList.stream().map((p) -> {
                List<PlateDto> collect = sort.stream().filter((s) ->
                        s.getParentId().equals(p.getPlateId())
                ).map((s) -> {
                    PlateDto plateDto = new PlateDto();
                    plateDto.setSortId(s.getSortId());
                    plateDto.setMenuName(s.getSortName());
                    return plateDto;
                }).collect(Collectors.toList());
                PlateDto plateDto = new PlateDto();
                plateDto.setMenuName(p.getPlateName());
                plateDto.setSortList(collect);
                return plateDto;
            }).collect(Collectors.toList());
            return collect1;
        }catch (NullPointerException e){
            System.out.println("查询失败或者数据库信息空！");
        }
        return plateDtosList;
    }

    /**
     * 《个人页面》
     * 根据前端传递的token获取再个人页面栏显示出的一系列栏目
     *
     * @param token
     * @return
     */
    @Override
    public List<ColumnPersonalShowDto> getPersonalShow(String token) {

        String userId = redisRepository.selectAccessToken(token);
        List<ColumnPersonalShowDto> columnPersonalShowDtoList = new ArrayList<>();
        try {
            List<ColumnEntity> columnEntityList = columnMapper.selectAllDataByUserId(userId);
            for(int i = 0 ; i < columnEntityList.size() ; i ++){
                ColumnPersonalShowDto columnShowDto = new ColumnPersonalShowDto();
                columnShowDto.setColumnName(columnEntityList.get(i).getColumnName());
                columnShowDto.setColumnLogo(columnEntityList.get(i).getColumnLogo());
                columnShowDto.setColumnType(columnEntityList.get(i).getColumnType());
                columnShowDto.setLicense(columnEntityList.get(i).getLicense());
                columnShowDto.setWebIntroduce(columnEntityList.get(i).getWebIntroduce());
                columnShowDto.setColumnId(columnEntityList.get(i).getColumnId());
                columnShowDto.setVerify(columnEntityList.get(i).getVerify());
                columnPersonalShowDtoList.add(columnShowDto);
            }
        }catch (NullPointerException e){
            System.out.println("查询失败或者数据库信息空！");
        }
        return columnPersonalShowDtoList;
    }


    @Override
    public MessageSuccessDto updateColumn(UpdateColumnForm updateColumnForm, String userId) {

        ColumnEntity columnEntity = columnMapper.selectByColumnId(updateColumnForm.getColumnId());
        if(!columnEntity.getUserId().equals(userId)){
            throw new SysException("系统错误！");
        }
        IntroduceEntity introduceEntity = introduceMapper.selectAllData(columnEntity.getIntroduceId());
        System.out.println(introduceEntity.getUpdateLog().trim());
        String updateLog = introduceEntity.getUpdateLog().trim()+"``"+new SimpleDateFormat("yyyy-MM-dd HH:mm")
                .format(new Date())+":"+updateColumnForm.getUpdateLog();
        columnMapper.updateColumn(updateColumnForm.getColumnId(),updateColumnForm.getColumnLogo(),
                updateColumnForm.getColumnName(),updateColumnForm.getColumnType(),
                updateColumnForm.getColumnWeb(), updateColumnForm.getLicense(),
                updateColumnForm.getParentId(), updateColumnForm.getShowPic(),
                updateColumnForm.getWebIntroduce());
        introduceEntity.setBriefIntro(updateColumnForm.getBriefIntro());
        introduceEntity.setCharacter(updateColumnForm.getCharacter());
        introduceEntity.setFunction(updateColumnForm.getFunction());
        introduceEntity.setUpdateLog(updateLog);
        introduceMapper.updateIntroduceById(columnEntity.getIntroduceId(),updateColumnForm.getBriefIntro(),
                updateColumnForm.getCharacter(),updateColumnForm.getFunction(),updateLog);

        MessageSuccessDto messageSuccessDto = new MessageSuccessDto();
        messageSuccessDto.setMessage("修改成功!");
        return messageSuccessDto;
    }
}
